<template>

  <el-dialog :title="$t('Token')" :visible.sync="tokenVisible" width="400px">
    <el-alert type="warning" :closable="false">{{ $t('TokenUse') }}</el-alert>
    <el-form ref="tokenForm" :model="token" label-position="left" label-width="100px">
      <el-form-item :label="$t('Role')">
        <el-radio-group v-model="token.roleId">
          <el-radio v-for="role in tokenRoles" :key="'role_'+role.roleId" :label="role.roleId">
            {{ role.roleName }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="buildToken">{{ $t('BuildToken') }}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
  import systemUserAPI from "@/api/system/user";
  export default {
    name: 'UserTokenDialog',
    data() {
      return {
        token: {
          roleId: null,
          userId: null
        },
        tokenRules: {
          roleId: [{
            require: true
          }]
        },
        tokenVisible: false,
        tokenRoles: [],
      }
    },
    methods: {
      show(row) {
        const vm = this;
        const userId = row.userId;
        systemUserAPI.getUser(userId).then((response) => {
          const token = response.data.token;
          vm.tokenRoles = [].concat(response.data.roles)
          vm.token.userId = userId
          if (vm.tokenRoles.length > 0) {
            vm.token.roleId = vm.tokenRoles[0].roleId
          }
          if (!token) {
            vm.tokenVisible = true;
            return;
          }
          vm.$confirm(token, vm.$t("Token"), {
            type: "success",
            cancelButtonText: vm.$t('Close'),
            confirmButtonText: vm.$t('Rebuild')
          }).then(() => {
            vm.tokenVisible = true;
          })
        });
      },
      buildToken() {
        const vm = this
        this.$refs['tokenForm'].validate(valid => {
          if (!valid) {
            return
          }
          systemUserAPI.createToken(this.token).then(res => {
            vm.tokenVisible = false
            vm.$alert(res.data.token, vm.$t("Token"), {
              type: "success"
            })
          })
        })
      }
    }
  }

</script>
